<route lang="json5" type="page">
  {
    layout: 'default',
    style: {
      navigationBarTitleText: '2024秋下续报',
    },
    anonymous: false
  }
</route>

<script lang="ts" setup>
import { useToast } from 'wot-design-uni'
import http from '@/utils/http'
import { getWxOpenId } from '@/apis'

const toast = useToast()

const model = reactive({
  openid: null,
  studentId: null,
  classStudentId: null,
  classId: null,
  teacherId: null,
  className: null,
  grade: null,
  subject: null,
  originalTotalPrice: null,
  actualTotalPrice: null,
})

const onClassStudentChange = (event) => {
  model.classStudentId = event.detail.value
}

// 支付
const disabled = computed(() => {
  return !model.studentId || !model.classStudentId
})
const loading = ref(false)
const onSubmit = () => {
  loading.value = true
  console.log({model})
  uni.login({
    provider: 'weixin',
    success: async (res) => {
      console.log(res)
      if (!res.code) {
        toast.error('获取微信code失败')
        loading.value = false
        return
      }
      const sessionRes = await getWxOpenId(res.code)
      model.openid = sessionRes.openid
      http.post('/temp/pay/create', model).then((orderInfo) => {
        console.log({ orderInfo })
        uni.requestPayment({
          provider: 'wxpay',
          ...orderInfo,
          success: () => {
            uni.navigateTo({url:'/pages/result/success'})
            // toast.success('支付成功!')
          },
          fail: (fail) => {
            console.warn('支付失败: ', fail)
            toast.error('支付失败!')
          },
        })
      }).finally(() => {
        loading.value = false
        // getClassList()
      })
    },
    fail: (fail) => {
      console.log('uni.login调用失败: {}', fail)
      loading.value = false
    },
  })
}

watch(() => model.classStudentId, () => {
  if(!model.classStudentId) {
    return
  }
  for (const item of classList.value) {
    if (item.id === model.classStudentId) {
      model.teacherId = item.classDetail.teacherId
      model.className = computeClassName(item.classDetail)
      model.grade = item.classDetail.grade
      model.subject = item.classDetail.subjectId
      model.classId = item.classDetail.id
      model.originalTotalPrice = computeClassPrice(item.classDetail)
      model.actualTotalPrice = model.originalTotalPrice
    }
  }
})


// 学生列表
const studentList = ref([])
const getStudentList = () => {
  http.get('/p/user/getStudentList').then((res) => {
    studentList.value = res
    if (studentList.value.length > 0) {
      model.studentId = studentList.value[0].id
    }
  }).catch(err => {
    classList.value = []
    toast.error('获取学生信息失败')
  })
}

watch(() => model.studentId, () => {
  if(!model.studentId) {
    return
  }
  model.classStudentId = null
  getClassList()
}, { immediate: true })

// 班级列表
const classList = ref([])
const getClassList = () => {
  const data = {
    studentId: model.studentId,
    subjectIdList: ['1', '10000000'],
    category: 1,
    season: 3,
    statusList: [0, 1]
  }
  http.get('https://www.bingxuewenhua.com/api/temp/getStudentClass', data).then((res) => {
    classList.value = res
    if (classList.value.length > 0) {
      const item = classList.value.find(item => !item.nextPeriodEnrolled)
      if(item) {
        model.classStudentId = item.id
      }
    }
  }).catch(err => {
    classList.value = []
    toast.error('获取报名信息失败')
  })
}

const computeClassPrice = (classDetail: any) => {
  switch(classDetail.grade) {
    case 1:
    case 2:
      return 2400
    case 3:
    case 4:
    case 5:
      return 3120
    case 6:
      return 2320
    case 7:
      return 3120
  }
}

const computeClassName = (classDetail: any) => {
  return classDetail.name.replace('数学', '创新思维')
}

onShow(() => {
  getStudentList()
})
</script>

<template>  
  <view class="pb-safe">
    <view class="section">
      报名学生
    </view>
    <view class="bg-white px">
      <radio-group v-if="studentList.length > 0">
        <view v-for="(item, index) in studentList" :key="index" class="cell h-44rpx flex-row-between-center" @click="model.studentId = item.id">
          <view>{{ item.name }}</view>
          <view>
            <radio :value="item.id" :checked="item.id === model.studentId"/>
          </view>
        </view>
      </radio-group>
      <wd-status-tip v-else image="search" tip="未查询到学生信息，如有错误请联系工作人员" />
    </view>
    <view class="section">
      报名班级
    </view>
    <view class="bg-white px">
      <radio-group v-if="classList.length > 0" @change="onClassStudentChange">
        <view v-for="(item, index) in classList" :key="index" class="cell h-44rpx flex-row-between-center" @click="model.classStudentId = item.id">
          <view class="text-sm">{{ computeClassName(item.classDetail) }}</view>
          <view v-if="item.nextPeriodEnrolled" class="w-320rpx flex-row-end-center">
            <text class="text-primary">
              已续报
            </text>
          </view>
          <view v-else class="w-320rpx flex-row-end-center">  
            <text class="mx-sm text-red">
              {{ computeClassPrice(item.classDetail) }}元
            </text>
            <radio :value="item.id" :checked="item.id === model.classStudentId" />
          </view>
        </view>
      </radio-group>
      <wd-status-tip v-else image="search" tip="未查询到学生信息，如有错误请联系工作人员" />
    </view>

    <button class="bg-primary btn mx mt" type="primary" :loading="loading" :disabled="disabled" @click="onSubmit">
      在线支付
    </button>
  </view>
</template>

<style lang="scss" scoped>
  //
  .cell {
    border-bottom: 1px solid #EEE;
    height: 120rpx;
  }
  .btn {
    background: $uni-color-primary;
  }
</style>
